<template>
    <div class="profile-info">
        <van-nav-bar title="个人资料" left-text="返回" left-arrow @click-left="onClickLeft" right-text="保存"
            @click-right="saveUserInfo" />

        <van-form @submit="saveUserInfo">
            <!-- 头像 -->
            <div class="avatar-field">
                <span class="field-label">头像</span>
                <div class="avatar-wrapper" @click="showAvatarPopup = true">
                    <img :src="formState.avatar" class="user-avatar" />
                    <van-icon name="arrow" class="arrow-icon" />
                </div>
            </div>

            <!-- 用户名 -->
            <van-cell-group inset>
                <van-field v-model="formState.username" name="username" label="用户名" placeholder="请输入用户名" readonly />

                <!-- 昵称 -->
                <van-field v-model="formState.nickname" name="nickname" label="昵称" placeholder="请输入昵称"
                    :rules="[{ required: true, message: '请输入昵称' }]" />

                <!-- 性别 -->
                <van-field v-model="formState.gender" is-link readonly name="gender" label="性别" placeholder="请选择性别"
                    @click="showGenderPicker = true" />

                <!-- 生日 -->
                <van-field v-model="formState.birthday" is-link readonly name="birthday" label="生日" placeholder="请选择生日"
                    @click="showCalendar = true" />

                <!-- 手机号 -->
                <van-field v-model="formState.phone" name="phone" label="手机号" placeholder="请输入手机号" />

                <!-- 邮箱 -->
                <van-field v-model="formState.email" name="email" label="邮箱" placeholder="请输入邮箱" />

                <!-- 所在地 -->
                <van-field v-model="formState.address" name="address" label="所在地" placeholder="请输入所在地" />

                <!-- 个性签名 -->
                <van-field v-model="formState.signature" name="signature" label="个性签名" type="textarea" maxlength="50"
                    placeholder="请输入个性签名" show-word-limit rows="2" />
            </van-cell-group>
        </van-form>

        <!-- 头像选择弹窗 -->
        <van-popup v-model:show="showAvatarPopup" round position="bottom" :style="{ height: '30%' }">
            <div class="avatar-upload">
                <div class="popup-title">更换头像</div>
                <div class="upload-options">
                    <div class="upload-btn" @click="triggerFileInput('camera')">
                        <van-icon name="photograph" size="24" />
                        <span>拍照</span>
                    </div>
                    <div class="upload-btn" @click="triggerFileInput('album')">
                        <van-icon name="photo" size="24" />
                        <span>从相册选择</span>
                    </div>
                    <input type="file" ref="fileInputRef" accept="image/*" class="hidden-input"
                        @change="onFileChange" />
                </div>
                <van-button block round type="default" class="cancel-btn"
                    @click="showAvatarPopup = false">取消</van-button>
            </div>
        </van-popup>

        <!-- 性别选择器 -->
        <van-popup v-model:show="showGenderPicker" round position="bottom">
            <van-picker title="选择性别" :columns="genderOptions" @confirm="onGenderConfirm"
                @cancel="showGenderPicker = false" />
        </van-popup>

        <!-- 日期选择器 -->
        <van-calendar v-model:show="showCalendar" :min-date="minDate" :max-date="maxDate" @confirm="onDateConfirm"
            :show-confirm="true" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'
import useUserStore from '@/stores/modules/user'
import { uploadUserAvatar } from '@/mocks'

const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const fileInputRef = ref(null)
const currentInputType = ref('')

// 表单数据
const formState = reactive({
    username: '',
    nickname: '',
    gender: '',
    birthday: '',
    phone: '',
    email: '',
    address: '',
    signature: '',
    avatar: ''
})

// 弹窗控制
const showAvatarPopup = ref(false)
const showGenderPicker = ref(false)
const showCalendar = ref(false)

// 选项数据
const genderOptions = [
    { text: '男', value: '男' },
    { text: '女', value: '女' },
    { text: '保密', value: '保密' }
]
const minDate = new Date(1950, 0, 1)
const maxDate = new Date()

// 返回按钮
const onClickLeft = () => {
    router.back()
}

// 初始化
onMounted(() => {
    initFormData()
})

// 在每次页面激活时也初始化数据
onActivated(() => {
    initFormData()
})

// 初始化表单数据
const initFormData = () => {
    // 确保头像字段存在
    formState.avatar = userInfo.value.avatar || ''

    Object.keys(formState).forEach(key => {
        if (userInfo.value[key] !== undefined) {
            formState[key] = userInfo.value[key]
        }
    })
}

// 触发文件输入框点击
const triggerFileInput = (type) => {
    currentInputType.value = type
    // 根据类型设置接受的文件类型
    if (type === 'camera') {
        fileInputRef.value.setAttribute('capture', 'camera')
    } else {
        fileInputRef.value.removeAttribute('capture')
    }
    fileInputRef.value.click()
}

// 处理文件选择变更
const onFileChange = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    // 检查文件类型
    if (!file.type.includes('image')) {
        showFailToast('请选择图片文件')
        return
    }

    // 检查文件大小 (最大 5MB)
    if (file.size > 5 * 1024 * 1024) {
        showFailToast('图片大小不能超过 5MB')
        return
    }

    // 显示加载提示
    showLoadingToast({
        message: '上传中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 调用模拟上传接口
        const result = await uploadUserAvatar(file)

        if (result && result.data && result.data.avatarUrl) {
            // 更新用户头像
            await userStore.updateAvatar(result.data.avatarUrl)

            // 立即更新页面上的头像显示
            formState.avatar = result.data.avatarUrl

            showSuccessToast('头像上传成功')
        } else {
            showFailToast('头像上传失败')
        }

        // 清空文件输入值，以便再次选择同一文件
        event.target.value = ''
        showAvatarPopup.value = false
        closeToast()
    } catch (error) {
        console.error('头像处理错误:', error)
        showFailToast('头像处理失败')
        closeToast()
    }
}

// 性别选择确认
const onGenderConfirm = (value) => {
    formState.gender = value.selectedOptions[0].text
    showGenderPicker.value = false
}

// 日期选择确认
const onDateConfirm = (value) => {
    formState.birthday = formatDate(value)
    showCalendar.value = false
}

// 格式化日期
const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 保存用户信息
const saveUserInfo = async () => {
    showLoadingToast({
        message: '保存中...',
        forbidClick: true,
        duration: 0
    })

    try {
        const result = await userStore.updateUserInfo(formState)
        if (result.success) {
            showSuccessToast('保存成功')
            setTimeout(() => {
                router.back()
            }, 1000)
        } else {
            showFailToast(result.message || '保存失败')
        }
    } catch (error) {
        console.error('保存错误:', error)
        showFailToast('保存失败')
    } finally {
        closeToast()
    }
}
</script>

<style lang="less" scoped>
.profile-info {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 20px;
}

.avatar-field {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    margin-bottom: 12px;
}

.field-label {
    font-size: 14px;
}

.avatar-wrapper {
    display: flex;
    align-items: center;
}

.user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 8px;
}

.arrow-icon {
    color: #969799;
}

.avatar-upload {
    padding: 20px;
}

.popup-title {
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
}

.upload-options {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
}

.upload-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px;
    width: 100px;
}

.upload-btn span {
    margin-top: 8px;
}

.cancel-btn {
    margin-top: 16px;
}

.hidden-input {
    display: none;
}
</style>